const axios = require('axios');
const configService = require('./configService');

class ShoplusService {
  constructor() {
    this.baseURL = 'https://www.shoplus.net/api/v1';
    // 不再直接存储authToken，而是从配置服务获取
  }

  /**
   * 获取当前有效的authToken
   */
  getEffectiveAuthToken(overrideToken = null) {
    return configService.getEffectiveAuthToken(overrideToken);
  }

  /**
   * 检查token是否过期
   */
  isTokenExpired(token = null) {
    return configService.isTokenExpired(token);
  }

  /**
   * 清理搜索关键词，移除特殊字符和过长的内容
   */
  cleanKeyword(keyword) {
    if (!keyword) return '';

    // 移除方括号和其他特殊字符
    let cleaned = keyword
      .replace(/[\[\]]/g, '') // 移除方括号
      .replace(/[^\w\s-]/g, ' ') // 移除除字母数字空格连字符外的特殊字符
      .replace(/\s+/g, ' ') // 合并多个空格
      .trim();

    // 限制长度，取前几个关键词
    const words = cleaned.split(' ');
    if (words.length > 6) {
      cleaned = words.slice(0, 6).join(' ');
    }

    // 限制总长度
    if (cleaned.length > 50) {
      cleaned = cleaned.substring(0, 50).trim();
    }

    return cleaned;
  }

  /**
   * 根据关键词搜索商品
   */
  async searchProducts(keyword, overrideToken = null) {
    try {
      // 获取当前有效的authToken
      const authToken = this.getEffectiveAuthToken(overrideToken);

      // 检查token是否过期
      if (this.isTokenExpired(authToken)) {
        return {
          success: false,
          error: 'TOKEN_EXPIRED',
          message: 'Shoplus授权token已过期，请更新token'
        };
      }

      // 清理关键词
      const cleanedKeyword = this.cleanKeyword(keyword);

      if (!cleanedKeyword) {
        return {
          success: false,
          error: 'INVALID_KEYWORD',
          message: '关键词为空或无效'
        };
      }

      // 对授权token进行编码
      const encodedAuthToken = encodeURIComponent(JSON.stringify(authToken));

      const url = `${this.baseURL}/product/search`;

      // 修正请求参数格式
      const params = {
        cursor: 0,
        keyword: cleanedKeyword,
        is_commerce: false,
        sort: 71,
        sort_type: 'DESC'
      };

      // 修正请求头格式
      const headers = {
        'authorized-token': encodedAuthToken,
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7',
        'Cache-Control': 'no-cache',
        'Pragma': 'no-cache',
        'Referer': 'https://www.shoplus.net/',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest'
      };

      console.log('原始关键词:', keyword);
      console.log('清理后关键词:', cleanedKeyword);
      console.log('使用token用户:', authToken.name);

      const response = await axios.get(url, {
        params: params,
        headers: headers,
        timeout: 30000,
        validateStatus: function (status) {
          return status >= 200 && status < 500;
        }
      });

      console.log('API响应状态:', response.status);

      // 检查是否返回HTML错误页面
      if (typeof response.data === 'string' && response.data.includes('<!doctype html>')) {
        console.error('收到HTML错误页面，可能是认证失败或请求格式错误');
        return {
          success: false,
          error: 'INVALID_REQUEST_FORMAT',
          message: '请求格式错误或认证失败，收到HTML错误页面',
          httpStatus: response.status
        };
      }

      if (response.status === 200 && response.data && response.data.code === 0) {
        return {
          success: true,
          data: response.data.data || [],
          message: '搜索成功'
        };
      } else {
        return {
          success: false,
          error: response.data?.msg || `HTTP_${response.status}`,
          message: response.data?.msg_detail || `HTTP错误: ${response.status}`,
          responseData: response.data,
          httpStatus: response.status
        };
      }

    } catch (error) {
      console.error('Shoplus API 搜索失败:', error.message);

      if (error.response) {
        console.error('响应状态:', error.response.status);
        console.error('响应数据:', error.response.data);

        if (typeof error.response.data === 'string' && error.response.data.includes('<!doctype html>')) {
          return {
            success: false,
            error: 'AUTHENTICATION_FAILED',
            message: 'Shoplus API认证失败，请检查token是否正确',
            httpStatus: error.response.status
          };
        }
      }

      return {
        success: false,
        error: error.code || 'NETWORK_ERROR',
        message: error.message || '网络请求失败'
      };
    }
  }

  /**
   * 解析商品数据，提取需要的字段
   */
  parseProductData(productData) {
    if (!productData || productData.length === 0) {
      return null;
    }

    // 取第一个搜索结果
    const product = productData[0];

    return {
      rank: product.rank || 0,
      priceUsd: this.parsePrice(product.price_usd),
      price: this.parsePrice(product.price),
      sellerName: product.seller_name || '',
      weekSoldCount: product.week_sold_count || 0,
      weekSales: this.parseSalesAmount(product.week_sales),
      weekSalesUsd: this.parseSalesAmount(product.week_sales_usd),
      totalSalesUsd: this.parseSalesAmount(product.total_sales_usd),
      totalSales: this.parseSalesAmount(product.total_sales),
      relatedVideos: product.related_videos || 0,
      relatedAuthor: product.related_author || 0
    };
  }

  /**
   * 解析价格字符串，提取数字
   */
  parsePrice(priceStr) {
    if (!priceStr) return 0;

    // 移除货币符号和其他字符，只保留数字和小数点
    const numStr = priceStr.toString().replace(/[^\d.]/g, '');
    const num = parseFloat(numStr);

    return isNaN(num) ? 0 : num;
  }

  /**
   * 解析销售额字符串，处理K、M等单位
   */
  parseSalesAmount(salesStr) {
    if (!salesStr) return 0;

    const str = salesStr.toString().toUpperCase();

    // 提取数字部分
    const numMatch = str.match(/[\d.]+/);
    if (!numMatch) return 0;

    const num = parseFloat(numMatch[0]);
    if (isNaN(num)) return 0;

    // 处理单位
    if (str.includes('K')) {
      return num * 1000;
    } else if (str.includes('M')) {
      return num * 1000000;
    } else if (str.includes('B')) {
      return num * 1000000000;
    }

    return num;
  }
}

module.exports = new ShoplusService();